<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 2016-04-11
 * Time: 9:22
 */
namespace common\traits;

use common\support\LogHelper;
use yii;
use yii\helpers\Inflector;
use yii\log\Logger;

/**
 * Class AnchorTrait
 * @package common\traits
 */
trait AnchorTrait
{
    private $anchorLogger = null;
    private $startLogTime;

    /**
     * @param LogHelper|null $anchorLogger
     */
    public function setAnchorLogger(LogHelper $anchorLogger = null)
    {
        if ($anchorLogger === null) {
            $class = get_called_class();
            $class = explode('\\', $class);
            $className = Inflector::camel2id(end($class), '_');
            $logfile = sprintf('%s/logs/%s/%s.log', Yii::$app->getRuntimePath(), $className, date('Y_m_d'));

            $anchorLogger = new LogHelper([
                'flushInterval' => 1000,
                'logFile'       => $logfile,
            ]);
        }

        $this->anchorLogger = $anchorLogger;
    }

    private function checkAnchorLogger()
    {
        return $this->anchorLogger !== null;
    }

    public function startTimePoint($message = '开始')
    {
        $this->startLogTime = microtime(true);
        $message = sprintf(str_repeat('#', 20) . ' ' . $message . ' ' . str_repeat('#', 20));
        $this->anchorlog($message);
    }

    /**
     * 标记时间点
     * @param $message
     */
    public function anchorTimePoint($message)
    {
        if ($this->startLogTime == null) {
            $this->startLogTime = microtime(true);
        }

        $useTime = round(microtime(true) - $this->startLogTime, 3);
        $message = sprintf('%4.3f %s', $useTime, $message);

        $this->anchorlog($message);
    }

    public function endTimePoint($message = '结束')
    {
        $useTime = round(microtime(true) - $this->startLogTime, 3);
        $this->startLogTime = null;
        $message = sprintf('%4.3f %s', $useTime, $message) . PHP_EOL;
        //$message = sprintf(str_repeat('#', 20) . ' ' . $message . ' ' . str_repeat('#', 20) . PHP_EOL);

        $this->anchorlog($message);
    }

    private function anchorlog($message, $level = Logger::LEVEL_INFO, $category = null)
    {
        if (!$this->checkAnchorLogger()) {
            return;
        }

        if ($category === null) {
            $appPaths = explode("/", str_replace(['\\', '/'], '/', Yii::getAlias('@app')));
            $category = end($appPaths);
        }

        return $this->anchorLogger->log($message, $level, $category);
    }
}
